<?php

namespace addons\qingdongams\controller;

use addons\qingdongams\model\Event;
use addons\qingdongams\model\Message as MessageModel;
use addons\qingdongams\model\Notice;
use addons\qingdongams\model\ExamineRecord;
use addons\qingdongams\model\Record;
use addons\qingdongams\model\ReceivablesPlan;
/**
 * @desc 操作文档：https://doc.fastadmin.net/qingdongams
 * @desc 软件介绍：https://www.fastadmin.net/store/qingdongams.html
 * @desc 售后微信：qingdong_crm
 */
/**
 * 通知接口
 */
class Message extends StaffApi {
	protected $noNeedLogin = [];
	protected $noNeedRight = [];


	//获取工作报告通知列表
	public function getWorkreportMessage() {
		$limit = input("limit/d", 10);

		$where = ['to_staff_id' => $this->auth->id, 'relation_type' => MessageModel::WORKREPORT_TYPE];

		$records = MessageModel::where($where)
            ->with(['fromStaff','examine','workreport'])
            ->order('status asc,id desc')
            ->field('id,from_staff_id,relation_id,status,content,send_time')->paginate($limit);

		$this->success('请求成功', $records);
	}

    //待办日程
	public function getStartEvent(){
        //待办日程
        $eventWhere = [
            'status' => ['in', [0, 1]],
            'start_time' => ['lt', date('Y-m-d', strtotime('+1 day'))],
//            'end_time' => ['gt', date('Y-m-d H:i:s')],
            'staff_id' => $this->auth->id,
        ];
        $event = Event::where($eventWhere)->with([
            'staff',
            'customer',
        ])->order('id desc')->select();
        $event=collection($event)->toArray();
        foreach ($event as $k => $v) {
            $v['level'] = Event::getLevel($v['level']);
            $v['status'] = Event::getStatus($v['status']);

            $event[$k] = $v;
        }
        $this->success('请求成功', $event);
    }

    //逾期日程
	public function getOverEvent(){
        //逾期日程
        $overEventsWhere=[
            'start_time' => ['lt', date('Y-m-d', strtotime('+1 day'))],
            'end_time' => ['lt', date('Y-m-d H:i:s')],
            'status'   => ['in', [0, 1]],
            'staff_id'=>$this->auth->id,
        ];

        $event = Event::where($overEventsWhere)->with([
            'staff',
            'customer'
        ])->order('id desc')->select();
        $event=collection($event)->toArray();
        foreach ($event as $k => $v) {
            $v['level'] = Event::getLevel($v['level']);
            $v['status'] = Event::getStatus($v['status']);

            $event[$k] = $v;
        }
        $this->success('请求成功', $event);
    }

    //工作动态
    public function getWorkSignin(){
        $limit = input("limit/d", 10);

        $where = ['to_staff_id' => $this->auth->id, 'relation_type' => MessageModel::RECORD_TYPE];

        $records = MessageModel::where($where)
            ->with(['fromStaff','examine'])
            ->order('status asc,id desc')->paginate($limit);

        $this->success('请求成功', $records);
    }

    //发送传阅消息
    public function sendMessage(){
        $relation_type=input('relation_type');
        $relation_id=input('relation_id');
        $staff_id=input('staff_id');
        $staff_ids=explode(',',$staff_id);

        $model=new MessageModel();
        switch ($relation_type) {
            case $model::CONSUME_TYPE://费用
                $rowModel = new \addons\qingdongams\model\Consume();
                break;
            case $model::CONTRACT_TYPE://订单
                $rowModel = new \addons\qingdongams\model\Contract();
                break;
            case $model::RECEIVABLES_TYPE://回款
                $rowModel = new \addons\qingdongams\model\Receivables();
                break;
            case $model::ACHIEVEMENT_TYPE://业绩目标
                $rowModel = new \addons\qingdongams\model\AchievementRecords();
                break;
            case $model::EVENT_TYPE://日程
                $rowModel = new \addons\qingdongams\model\Event();
                break;
            case $model::WORKORDER_TYPE://工单
                $rowModel = new \addons\qingdongams\model\Workorder();
                break;
            case $model::QUOTE_TYPE://报价单
                $rowModel = new \addons\qingdongams\model\Quote();
                break;
            case $model::CUSTOMER_TYPE://客户
                $rowModel = new \addons\qingdongams\model\Customer();
                break;
            case $model::APPROVAL_TYPE://审批
                $rowModel = new \addons\qingdongams\model\Approval();
                break;
            case $model::PARTS_TYPE://配件
                $rowModel = new \addons\qingdongams\model\Parts();
                break;
            case $model::PARTS_STOCK_RELOAD_TYPE://配件
                $rowModel = new \addons\qingdongams\model\PartsStockReload();
                break;
            default:
                $this->error('参数错误');
        }
        $row=$rowModel->get($relation_id);
        if(empty($row)){
            $this->error('信息不存在');
        }
        switch ($relation_type) {
            case $model::CONSUME_TYPE://费用
                $content=$this->auth->name."传阅费用《{$row['number']}》，邀请您审阅";
                break;
            case $model::CONTRACT_TYPE://订单
                $content=$this->auth->name."传阅订单《{$row['num']}》，邀请您审阅";
                break;
            case $model::RECEIVABLES_TYPE://回款
                $content=$this->auth->name."传阅回款《{$row['number']}》，邀请您审阅";
                break;
            case $model::ACHIEVEMENT_TYPE://业绩目标
                $content=$this->auth->name."传阅目标《{$row['year']}》，邀请您审阅";
                break;
            case $model::EVENT_TYPE://日程
                $content=$this->auth->name."传阅{$row['event_type']}《{$row['title']}》，邀请您审阅";
                break;
            case $model::WORKORDER_TYPE://工单
                $content=$this->auth->name."传阅{$row['workorder_type']}《{$row['title']}》，邀请您审阅";
                break;
            case $model::PROOF_TYPE://打样
                $content=$this->auth->name."传阅打样《{$row['process_number']}》，邀请您审阅";
                break;
            case $model::QUOTE_TYPE://报价单
                $content=$this->auth->name."传阅报价单《{$row['number']}》，邀请您审阅";
                break;
            case $model::CUSTOMER_TYPE://客户
                $content=$this->auth->name."传阅客户《{$row['name']}》，邀请您审阅";
                break;
            case $model::APPROVAL_TYPE://审批
                $content=$this->auth->name."传阅审批，邀请您审阅";
                break;
            case $model::PARTS_TYPE://配件
                $content=$this->auth->name."传阅配件信息，邀请您审阅";
                break;
            case $model::PARTS_STOCK_RELOAD_TYPE://配件
                $content=$this->auth->name."传阅配件信息，邀请您审阅";
                break;
            default:
                $this->error('参数错误');
        }

        foreach ($staff_ids as $id){
            MessageModel::addMessage($relation_type,$relation_id,$id, $this->auth->id, $content);
        }

        $this->success('请求成功');
    }


    /**
     * 获取通知列表
     */
    public function getList()
    {
        $limit = input("limit/d", 10);

        $where = ['to_staff_id' => $this->auth->id ,'relation_type'=>['not in','examine,discuss,sign,comment,leadspool_achieve,invoice,add_lead,customer,workorder_achieve,leads_tranfer,leads_move_pool']];
        $records = MessageModel::where($where)->with(['fromStaff', 'examine'])->order('status asc,id desc')->paginate($limit);

        $this->success('请求成功', $records);
    }

    /**
     * 获取审批列表
     */
    public function getExamineRecord()
    {
        $limit = input("limit/d", 10);
        //订单审批，回款审批、业绩目标审批、办公审批 费用
        $relation_type = input('type');
        $status =  input('status',0);
        if($status == 1){
            $status = array('in','2,3');
        }
        $ids = ExamineRecord::where(['relation_type' => $relation_type,
            'status' => $status,
            'check_staff_id' => $this->auth->id])->column('id');
        $where = ['to_staff_id' => $this->auth->id, 'relation_id' => ['in', $ids], 'relation_type' => MessageModel::EXAMINE_TYPE];

        $records = MessageModel::where($where)->with(['fromStaff', 'examine'])->order('status asc,id desc')->paginate($limit);

        $this->success('请求成功', $records);
    }

    /**
     * 获取审批通知详情
     */
    public function getExamineInfo()
    {

        $data = [
            ExamineRecord::CONTRACT_TYPE => ['count' => 0, 'msg' => '暂无消息'],
            ExamineRecord::CONSUME_TYPE => ['count' => 0, 'msg' => '暂无消息'],
            ExamineRecord::RECEIVABLES_TYPE => ['count' => 0, 'msg' => '暂无消息'],
            ExamineRecord::APPROVAL_TYPE => ['count' => 0, 'msg' => '暂无消息'],
            ExamineRecord::ACHIEVEMENT_TYPE => ['count' => 0, 'msg' => '暂无消息'],
            ExamineRecord::CARD_TYPE => ['count' => 0, 'msg' => '暂无消息'],
            ExamineRecord::LEAVE_TYPE => ['count' => 0, 'msg' => '暂无消息'],

            ExamineRecord::QUOTE_TYPE => ['count' => 0, 'msg' => '暂无消息'],
            ExamineRecord::PARTS_TYPE => ['count' => 0, 'msg' => '暂无消息'],
            ExamineRecord::WORKORDER_TYPE => ['count' => 0, 'msg' => '暂无消息'],
            ExamineRecord::INVOICE_TYPE => ['count' => 0, 'msg' => '暂无消息'],
        ];
        foreach ($data as $type=>$v) {
            $ids = ExamineRecord::where(['status' => 0, 'check_staff_id' => $this->auth->id,
                'relation_type' => $type
            ])->column('id');
            $count = MessageModel::where(['to_staff_id' => $this->auth->id,'relation_id' => ['in', $ids],
                'relation_type' => MessageModel::EXAMINE_TYPE])
                ->count();
            if ($count) {
                $msg = MessageModel::where(['to_staff_id' => $this->auth->id, 'relation_id' => ['in', $ids],
                    'relation_type' => MessageModel::EXAMINE_TYPE])
                    ->order('id desc')
                    ->value('content');
                $data[$type] = ['count' => $count, 'msg' => $msg];
            }
        }

        $this->success('请求成功', $data);
    }

    /**
     * 获取通知详情
     */
    public function getInfo()
    {
        $leadsCount = MessageModel::where(['to_staff_id' => $this->auth->id,
            'relation_type' => ['not in','examine,discuss,sign,comment,leadspool_achieve,invoice,add_lead,customer,workorder_achieve,leads_tranfer,leads_move_pool'], 'status' => 0])->count();
        if ($leadsCount > 0) {//其他提醒消息
            $leadsDetail = MessageModel::where([
                'relation_type' => ['neq', MessageModel::EXAMINE_TYPE],
                'to_staff_id' => $this->auth->id,
                'status' => 0
            ])->order('id desc')->find();
        }

        $noticeWhere['read_staff_ids'] = ['not like', "%,{$this->auth->id},%"];

        $noticeCount = Notice::where($noticeWhere)->count();
        if ($noticeCount > 0) {
            $noticeDetail = Notice::where(['read_staff_ids' => ['not like', "%,{$this->auth->id},%"]])->order('id desc')->find();
        }

        $eventOne = Event::where([
            'type' => 1,
            'status' => ['in', [0, 1]],
            'start_time' => ['lt', date('Y-m-d', strtotime('+1 day'))],
            'staff_id|owner_staff_id' => $this->auth->id
        ])->count();
        //订单审批
        $contract = ExamineRecord::where([
            'relation_type' => ExamineRecord::CONTRACT_TYPE,
            'status' => 0,
            'check_staff_id' => $this->auth->id
        ])->count();
        //回款审批
        $receivables = ExamineRecord::where([
            'relation_type' => ExamineRecord::RECEIVABLES_TYPE,
            'status' => 0,
            'check_staff_id' => $this->auth->id
        ])->count();
        //费用审批
        $consume = ExamineRecord::where([
            'relation_type' => ExamineRecord::CONSUME_TYPE,
            'status' => 0,
            'check_staff_id' => $this->auth->id
        ])->count();
        //业绩目标审批
        $achievement = ExamineRecord::where([
            'relation_type' => ExamineRecord::ACHIEVEMENT_TYPE,
            'status' => 0,
            'check_staff_id' => $this->auth->id
        ])->count();
        //办公审批
        $approval = ExamineRecord::where([
            'relation_type' => ExamineRecord::APPROVAL_TYPE,
            'status' => 0,
            'check_staff_id' => $this->auth->id
        ])->count();
        //补卡审批
        $card = ExamineRecord::where([
            'relation_type' => ExamineRecord::CARD_TYPE,
            'status' => 0,
            'check_staff_id' => $this->auth->id
        ])->count();
        //请假审批
        $leave = ExamineRecord::where([
            'relation_type' => ExamineRecord::LEAVE_TYPE,
            'status' => 0,
            'check_staff_id' => $this->auth->id
        ])->count();
        //待发票审批
        $invoice = ExamineRecord::where([
            'relation_type'  => ExamineRecord::INVOICE_TYPE,
            'status'         => 0,
            'check_staff_id' => $this->auth->id
        ])->count();
        $receivablesPlan = ReceivablesPlan::where([
            'remind_date' => ['elt', date('Y-m-d')],
            'status' => 0,
            'owner_staff_id' => $this->auth->id
        ])->count();

        $eventsCount = Event::where([
            'start_time' => ['lt', date('Y-m-d', strtotime('+1 day'))],
            'end_time' => ['lt', date('Y-m-d', strtotime('+1 day'))],
            'status' => ['in', [0, 1]],
            'staff_id' => $this->auth->id,
        ])->count();

        $where['create_staff_id'] = $this->auth->id;
        $where['next_time'] = array(array('egt',date('Y-m-d 00:00:00')),array('lt',date('Y-m-d 23:59:59')));
        $where['follow_type'] = ['neq', '其它'];
        $where['status'] = 0;
        // 待跟进客户
        $where1['relation_type'] = 1;
        $customerlist = Record::where($where)->where($where1)->column('id');
        $customerlist1 = 0;
        if($customerlist){
            $whereExit['id'] = array('in',$customerlist);
            $whereExit['next_time'] = array('gt',date('Y-m-d 23:59:59'));
            $customerlist1 = Record::where($whereExit)->count();
        }
        $customer = count($customerlist) - $customerlist1;

        //待跟进订单
        $where2['relation_type'] = 3;
        $contractlist = Record::where($where)->where($where2)->column('id');
        $contractlist1 = 0;
        if($contractlist){
            $whereExitC['id'] = array('in',$contractlist);
            $whereExitC['next_time'] = array('gt',date('Y-m-d 23:59:59'));
            $contractlist1 = Record::where($whereExitC)->count();
        }
        $contracts = count($contractlist)-$contractlist1;
        //待跟进线索
        $where3['relation_type'] = 4;
        $leadlist = Record::where($where)->where($where3)->column('id');
        $leadlist1 = 0;
        if($leadlist){
            $whereExitL['id'] = array('in',$leadlist);
            $whereExitL['next_time'] = array('gt',date('Y-m-d 23:59:59'));
            $leadlist1 = Record::where($whereExitL)->count();
        }
        $lead = count($leadlist)-$leadlist1;
        //待跟进联系人
        $where4['relation_type'] = 2;
        $contactslist = Record::where($where)->where($where4)->column('id');
        $contactslist1 = 0;
        if($contactslist1){
            $whereExitCs['id'] = array('in',$contactslist);
            $whereExitCs['next_time'] = array('gt',date('Y-m-d 23:59:59'));
            $contactslist1 = Record::where($whereExitCs)->count();
        }
        $contacts = count($contactslist)-$contactslist1;
        //待跟进商机
        $where5['relation_type'] = 5;
        $businesslist = Record::where($where)->where($where5)->column('id');
        $businesslist1 = 0;
        if($businesslist1){
            $whereExitB['id'] = array('in',$businesslist);
            $whereExitB['next_time'] = array('gt',date('Y-m-d 23:59:59'));
            $businesslist1 = Record::where($whereExitB)->count();
        }
        $business = count($businesslist)-$businesslist1;
        //工作报告
        $workreportWhere=[
            'to_staff_id' => $this->auth->id,
            'status' => 0,
            'relation_type' => MessageModel::WORKREPORT_TYPE
        ];
        $workreportCount = MessageModel::where($workreportWhere)->count();
        if ($workreportCount > 0) {//提醒消息
            $workreportDetail = MessageModel::where($workreportWhere)->order('id desc')->find();
        }
        //提醒消息
        $data = [
            'leads' => ['count' => $leadsCount, 'msg' => $leadsDetail['content'] ?? '暂无消息'],//提醒消息
            'workreport' => ['count' => $workreportCount, 'msg' => $workreportDetail['content'] ?? '暂无消息'],//工作报告
            'examine' => ['count' => $contract + $receivables+$consume+$achievement+$approval+$card+$leave+$invoice,
                'msg' => '审批消息提醒'],//提醒消息
            'notice' => ['count' => $noticeCount, 'msg' => $noticeDetail['title'] ?? '暂无消息'],//系统公告
            'agent' => [
                'count' => $eventOne  + $receivablesPlan+ $customer + $contracts + $lead + $contacts + $business,
                'msg' => '您有新的待办事项需要处理！'
            ],//待办事项
            'task' => [
                'count' => $eventsCount,
                'msg' => '即将超时的任务提醒！'
            ],//超时任务
            'total' => $leadsCount  + $noticeCount + $eventOne + $contract + $receivables + $receivablesPlan + $eventsCount+ $customer + $contracts + $lead + $contacts + $business+$consume+$achievement+$approval+$card+$leave+$invoice,

            'userinfo' => $this->auth->getUserinfo()
        ];
        $this->success('请求成功', $data);
    }
}
